const ProductService = require("../../services/admin/ProductService");
const JWT = require("../../utils/JWT");
const path = require("path");
const fs = require("fs");

// 异步删除文件的函数
const deleteFile = (filePath) => {
  fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
      // 文件不存在，不需要删除
      console.log(`文件 ${filePath} 不存在，无需删除`);
    } else {
      // 文件存在，执行删除操作
      fs.unlink(filePath, (err) => {
        if (err) {
          // 删除失败，输出错误信息
          console.error(`删除文件 ${filePath} 失败`, err);
        } else {
          // 删除成功
          console.log(`文件 ${filePath} 删除成功`);
        }
      });
    }
  });
};

const ProductController = {
  add: async (req, res) => {
    const { title, introduction, detail } = req.body;
    const cover = req.file
      ? `/images/product/${req.file.filename}`
      : "/images/defaultUserImg.png";

    // 调用service模块更新数据
    await ProductService.add({
      title,
      introduction,
      detail,
      cover,
    });

    // 将存储结果告知前端
    res.send({ ActionType: "OK" });
  },
  deleteListItem: async (req, res) => {
    const result = await ProductService.deleteListItem({ _id: req.params.id });
    res.send({ ActionType: "OK" });
  },

  getListById: async (req, res) => {
    const result = await ProductService.getListById({
      _id: req.params?.id || null,
    });

    res.send({
      ActionType: "OK",
      data: result,
    });
  },

  getListOfPage: async (req, res) => {
    try {
      // 获取分页参数，默认为第1页，每页10条记录
      const searchValue = req.query.searchValue || ""; // 搜索字段
      const pageNo = parseInt(req.query.pageNo, 10) || 1; // 页码
      const limit = parseInt(req.query.limit, 10) || 10; // 每页数据量
      const sortField = req.query.sortField || "createdAt"; // 默认按创建时间排序
      const sortOrder = req.query.sortOrder || "asc"; // 默认升序 [desc|asc]

      const result = await ProductService.getListOfPage({
        searchValue,
        pageNo,
        limit,
        sortField,
        sortOrder,
      });

      res.send({
        ActionType: "OK",
        data: {
          pageNo,
          limit,
          ...result,
        },
      });
    } catch (error) {
      res.status(500).send({
        ActionType: "ERROR",
        message: "服务器错误",
      });
    }
  },

  putListItem: async (req, res) => {
    try {
      // 处理文件和数据
      let itemData = { ...req.body }; // 使用解构来复制req.body，避免直接修改它
      itemData.cover = req.file
        ? `/images/product/${req.file.filename}`
        : req.cover; // 构建图片的URL

      const currentItme = await ProductService.getListById({
        _id: itemData._id,
      });
      const oldCoverPath = currentItme[0].cover;

      // 删除旧的头像文件
      if (
        req.file &&
        oldCoverPath &&
        oldCoverPath !== "/images/defaultUserImg.png"
      ) {
        const oldAvatarFullPath = path.join(
          // __dirname, // 返回的是当前执行脚本所在的目录路径
          process.cwd(), // 获取当前工作目录，通常是项目根目录
          "public",
          "images",
          "product",
          path.basename(oldCoverPath)
        );
        deleteFile(oldAvatarFullPath);
      }
      const result = await ProductService.putList(itemData);
      res.send({
        ActionType: "OK",
      });
    } catch (error) {
      console.error("Error:", error);
      res.status(500).send({
        ActionType: "ERROR",
        message: "服务器错误",
        error: error.message,
      });
    }
  },

  publish: async (req, res) => {
    await ProductService.publish({
      ...req.body,
    });
    res.send({
      ActionType: "OK",
    });
  },
};

module.exports = ProductController;
